package com.zed.api.domain;

import com.zed.api.common.adpt.AdaptObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.io.Serializable;
import java.util.Objects;

/**
 * {@link AggreateRoot},聚合根对象
 *
 * @author Zed
 */
@SuppressWarnings("serial")
public abstract class AggreateRoot<I> extends AdaptObject
        implements Aggregatable<I>, ApplicationContextAware, Serializable {


    /* 该字段不支持序列化 */
    private transient ApplicationContext applicationContext;

    /**
     * 创建一个新实例
     */
    public AggreateRoot() {

    }

    /**
     * 初始化，派生类用于向字段注入本聚合根
     */
    protected void init() {
    }

    /**
     * 按{@code beanName}和{@code beanType}获取Bean实例
     *
     * @param <T>
     * @param beanName {@link String}, bean名称
     * @param beanType {@link Class}, bean类型
     * @return {@link T}
     */
    public <T> T getBean(String beanName, Class<T> beanType) {
        return this.getApplicationContext().getBean(beanName, beanType);
    }

    /**
     * 应用件上下文
     *
     * @return {@link ApplicationContext}
     */
    protected ApplicationContext getApplicationContext() {
        return Objects.requireNonNull(
                this.applicationContext, "\"applicationContext\" cannot be null, please set it.");
    }

    @Override
    public void setApplicationContext(ApplicationContext context) {
        this.applicationContext = context;
    }

    /**
     * 尝试初始化聚合根，对聚合根内的实体注入聚合根实例。
     *
     * @param target
     */
    @SuppressWarnings("rawtypes")
    public static <T> T tryInit(T target) {
        if (target != null) {
            if (target instanceof AggreateRoot) {
                ((AggreateRoot) target).init();
            }
        }
        return target;
    }
}
